package org.geektimes.projects.user.web.listener;

import org.geektimes.dependency.injection.function.ThrowableAction;
import org.geektimes.dependency.injection.web.context.ClassicComponentContext;
import org.geektimes.dependency.injection.web.context.ComponentContext;

import javax.jms.*;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.util.logging.Logger;

/**
 * @Author: jipeng
 * @Description:
 * @Date: Created in 2021/3/21 23:10
 */
public class XmlServletContextListener implements ServletContextListener {
    private final Logger logger = Logger.getLogger(getClass().getName());

    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        logger.info("===================== start XmlServletContextListener contextInitialized method =====================");

        ComponentContext context = ClassicComponentContext.getInstance();
        logger.info("所有的 JNDI 组件名称：[");
        context.getComponentNames().forEach(logger::info);
        logger.info("]");


        ConnectionFactory connectionFactory = context.getComponent("jms/activemq-factory");


        textJms(connectionFactory);
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {

    }

    private void textJms(ConnectionFactory connectionFactory){
        ThrowableAction.execute(()->{
//            testMessageProducer(connectionFactory);
            testMessageConsumer(connectionFactory);
        });
    }

    private void testMessageProducer(ConnectionFactory connectionFactory) throws JMSException {
        //通过 工厂 创建 连接
        Connection connection = connectionFactory.createConnection();
        connection.start();

        //通过连接创建会话
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

        //创建监听队列
        Destination destination = session.createQueue("TEST.FOO");

        //创建生产者
        MessageProducer producer = session.createProducer(destination);
        //消息保存模式
        producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);

        // Create a messages
        String text = "Hello world! From: " + Thread.currentThread().getName() + " : " + this.hashCode();
        //创建消息
        TextMessage message = session.createTextMessage(text);
        //发送消息
        producer.send(message);

        System.out.printf("producer ======= [Thread : %s] Sent message : %s\n", Thread.currentThread().getName(), message.getText());


//        //创建消费者
//        MessageConsumer consumer = session.createConsumer(destination);
////        message = (TextMessage) consumer.receive(10000);
//
//        consumer.setMessageListener(m ->{
//            TextMessage tm = (TextMessage) m;
//            try {
//                System.out.printf("consumer ======= [Thread : %s] Received : %s\n", Thread.currentThread().getName(), tm.getText());
//            } catch (JMSException e) {
//                throw new RuntimeException(e);
//            }
//        });


        session.close();
        connection.close();
    }

    private void testMessageConsumer(ConnectionFactory connectionFactory) throws JMSException {
        //通过 工厂 创建 连接
        Connection connection = connectionFactory.createConnection();
        connection.start();

        //通过连接创建会话
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

        //创建监听队列
        Destination destination = session.createQueue("TEST.FOO");

        //创建消费者
        MessageConsumer consumer = session.createConsumer(destination);
        consumer.setMessageListener(m ->{
            TextMessage tm = (TextMessage) m;
            try {
                System.out.printf("consumer ======= [Thread : %s] Received : %s\n", Thread.currentThread().getName(), tm.getText());
            } catch (JMSException e) {
                throw new RuntimeException(e);
            }
        });

        //消费者连接不能关闭
//        session.close();
//        connection.close();

    }


}
